﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

public class AtlasPacking
{

    [MenuItem("Assets/XFABManager/打包图集")]
    static void PackageAtlas()
    {
        //Debug.Log("打包图集");

        Object obj = Selection.activeObject;

        string path = AssetDatabase.GetAssetPath(obj);

        if (!AssetDatabase.IsValidFolder(path))
        {
            Debug.LogError("请选择一个文件夹!");
            return;
        }

        string[] sub_folders = AssetDatabase.GetSubFolders(path);

        Dictionary<string,List<string>> sub_folder_assets = new Dictionary<string, List<string>>();

        foreach (string folder in sub_folders) {
            string[] assets = AssetDatabase.FindAssets("t:Sprite", new string[] { folder });
            if (assets.Length == 0) continue;
            List<string> list = new List<string>();
            list.AddRange(assets);
 
            if (!sub_folder_assets.ContainsKey(folder))
               sub_folder_assets.Add(folder, list);
        }
         
        string[] sub_assets = AssetDatabase.FindAssets("t:Sprite", new string[] { path });
        List<string> directly_assets = new List<string>();
        foreach (string sub_asset in sub_assets) {

            bool isContain = false;
            foreach (List<string> v in sub_folder_assets.Values)
            {
                if (v.Contains(sub_asset)) { 
                    isContain = true;
                    break;
                }
            }

            if(isContain == false)
                directly_assets.Add(sub_asset);
        }


        // 创建一个目录 用来存放图集

        Debug.Log(path + " " + System.IO.Path.GetDirectoryName(path));

        string atlasPath = string.Format("{0}/{1}_Atlas", System.IO.Path.GetDirectoryName(path), System.IO.Path.GetFileNameWithoutExtension(path));

        if ( AssetDatabase.IsValidFolder(atlasPath) ) {
            AssetDatabase.DeleteAsset(atlasPath);
        }
        AssetDatabase.CreateFolder(System.IO.Path.GetDirectoryName(path), string.Format("{0}_Atlas", System.IO.Path.GetFileNameWithoutExtension(path)));

        foreach (var item in sub_folder_assets.Keys)
        {
            //Debug.Log(item);
            string folderName = System.IO.Path.GetFileName(item);
            string altasPath = string.Format("{0}/{1}Atlas.spriteatlas", atlasPath, folderName);

            CreateAtlas(sub_folder_assets[item], altasPath);
        }

        CreateAtlas(directly_assets,string.Format("{0}/{1}Atlas.spriteatlas", atlasPath, System.IO.Path.GetFileNameWithoutExtension(atlasPath)));

    
    }

    public static void CreateAtlas(List<string> assets_guids,string path, TextureImporterPlatformSettings platformSetting = null) {

        List<string> objects = new List<string>();

        foreach (var asset in assets_guids) {
            objects.Add( AssetDatabase.GUIDToAssetPath( asset)); 
        }
         
        CreateAtlasByAssetPath(objects.ToArray(), path, platformSetting);
    }

    public static void CreateAtlasByAssetPath(string[] assets, string path, TextureImporterPlatformSettings platformSetting = null)
    {
        List<Object> objects = new List<Object>();

        foreach (var asset in assets)
        {
            Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(asset);

            if (sprite != null && sprite.rect.width < 512 && sprite.rect.height < 512)
            {
                // 如果这个图片本身有多子图片 说明它本身就是一个图集 不需要再打进图集中
                if (AssetDatabase.LoadAllAssetsAtPath(asset).Length == 2)
                    objects.Add(sprite); 
            }
        }

        if (objects.Count <= 1) return; // 不需要打包图集

        SpriteAtlas atlas = new SpriteAtlas();
        atlas.SetIncludeInBuild(true);

        SpriteAtlasPackingSettings packSet = new SpriteAtlasPackingSettings();
        packSet.blockOffset = 1;
        packSet.enableRotation = false;
        packSet.enableTightPacking = false;
        packSet.padding = 2;

        atlas.SetPackingSettings(packSet);

        SpriteAtlasTextureSettings textureSet = new SpriteAtlasTextureSettings();

        textureSet.readable = false;
        textureSet.generateMipMaps = false;
        textureSet.sRGB = true;
        textureSet.filterMode = FilterMode.Bilinear;

        atlas.SetTextureSettings(textureSet);

        atlas.Add(objects.ToArray());

        if (platformSetting == null)
            platformSetting = new TextureImporterPlatformSettings()
            {
                maxTextureSize = 2048,
                format = TextureImporterFormat.Automatic,
                crunchedCompression = true,
                textureCompression = TextureImporterCompression.Compressed,
                compressionQuality = 50,
            };
         
        atlas.SetPlatformSettings(platformSetting);

        AssetDatabase.CreateAsset(atlas, path);

        AssetDatabase.Refresh();


    }

}
